﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.TenPayLibV3;
using Senparc.Weixin.MP.AdvancedAPIs;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using PlatWL.Data;
using PlatWL.Services.Tools;
using Senparc.Weixin;
using System.Xml.Linq;
using System.IO;
using System.Transactions;


namespace PlatWL.Services.Other
{
    public class WeixinManage
    {
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            if (errors == SslPolicyErrors.None)
                return true;
            return false;
        }

        private static TenPayV3Info _tenPayV3Info;
        public static TenPayV3Info TenPayV3Info
        {
            get
            {
                if (_tenPayV3Info == null)
                {
                    string wxappid = WXHelp.appid;
                    string wxappsecret = WXHelp.secret; // ConfigurationManager.AppSettings["wxappsecret"];
                    string wxmchid = WXHelp.mchid; // ConfigurationManager.AppSettings["wxmchid"];
                    string wxmchidkey = WXHelp.mchidkey; //ConfigurationManager.AppSettings["wxmchidkey"];
                    string TenPayV3Notify = WXHelp.tenpayv3notify; //ConfigurationManager.AppSettings["TenPayV3Notify"];


                    _tenPayV3Info = new TenPayV3Info(wxappid, wxappsecret, wxmchid, wxmchidkey, TenPayV3Notify);
                }
                return _tenPayV3Info;
            }
        }


        #region 微信授权登录，通过code找到用户信息
        public void GetUserInfoByCode(ref Msg_Result msg, string code,string refstr)
        {
            int refID = 0;
            Int32.TryParse(refstr, out refID);
            //添加事务

            using (TransactionScope ts = new TransactionScope())
            {
                OAuthUserInfo wxusr = WXHelp.GetUserInfoByCode(code);

                //判断openid是否存在
                var user = new pt_user_accountb().GetEntityFirst(d => d.OpenID == wxusr.openid);
                if (user != null) //openid存在
                {

                }
                else  //openid不存在
                {
                    var newUser = new pt_user_account();
                    newUser.OpenID = wxusr.openid;
                    newUser.NickName = wxusr.nickname;
                    newUser.Province = wxusr.province;
                    newUser.City = wxusr.city;
                    newUser.County = wxusr.country;
                    newUser.UserImg = wxusr.headimgurl;
                    if (wxusr.sex == 1)
                    {
                        newUser.Sex = "男";
                    }
                    else if (wxusr.sex == 2)
                    {
                        newUser.Sex = "女";
                    }
                    newUser.UserType = 1;
                    newUser.CRTime = DateTime.Now;
                    newUser.Balance = 0;
                    newUser.Point = 0;
                    newUser.Lev = 0;
                    newUser.UpID = 0;
                    newUser.Status = 0;
                    newUser.Deleted = 0;

                    newUser.IP = Tools.Common.GetIP();
                    newUser.IPLocation = Tools.Common.GetIPLocation(newUser.IP);
                    //if (!newUser.IPLocation.Contains("郑州"))
                    //{
                    //    newUser.Status = "-1";
                    //}
                    //if (refID > 0)
                    //{
                    //    newUser.RefID = refID;
                    //}

                    new pt_user_accountb().Insert(newUser);
                    user = newUser;
                


                }

                //gen token
                //为用户生成登录凭证
                string token = Tools.Common.GuID();
                new pt_auth_tokenb().Insert(new pt_auth_token()
                {
                    Client = -1,
                    UserID = user.ID,
                    Token = token,
                    TokenTime = DateTime.Now,
                    ExpireTime = DateTime.Now.AddDays(1),
                    ISAdmin = 0
                });


                string issubscribe = "0";
                //判断是否关注公众号
                if (WXHelp.ISSubscribe(user.OpenID))
                {
                    issubscribe = "1";
                }

                msg.result = new { token = token, issubscribe = issubscribe };

                ts.Complete();
            }


        }
        #endregion

        #region JSAPI分享接口权限
        /// <summary>
        /// JSAPI接口权限
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="Client"></param>
        /// <param name="url"></param>
        public void JSAPI(ref Msg_Result msg, string url)
        {
            msg.result = WXHelp.JSSDKGETSIGNAGURE(url);
        }
        #endregion

        #region 微信支付接口参数
        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="TradeType">JSAPI：微信内支付,MWEB：H5支付</param>
        /// <param name="orderid"></param>
        /// <param name="code"></param>
        public void GetPayJSAPI(ref Msg_Result msg, string TradeType, int orderid, string code)
        {
            try
            {
                //string userip = HttpContext.Current.Request.UserHostAddress;

                //var ord = new PT_Order_HeaderB().GetEntity(p => p.ID == orderid);
                //if (ord == null)
                //{
                //    msg.error = "订单信息错误！";
                //    return;
                //}
                //if (ord.Status != 0)
                //{
                //    msg.error = "订单状态有误,或您已支付.";
                //    return;
                //}
                //string openid = "";
                //if (TradeType == "JSAPI")
                //{
                //    if (string.IsNullOrEmpty(code))
                //    {
                //        msg.error = "您拒绝了授权！";
                //        return;
                //    }
                //    //通过，用code换取access_token
                //    var openIdResult = OAuthApi.GetAccessToken(TenPayV3Info.AppId, TenPayV3Info.AppSecret, code);
                //    if (openIdResult.errcode != ReturnCode.请求成功)
                //    {
                //        msg.error = "错误：" + openIdResult.errmsg;
                //        return;
                //    }
                //    openid = openIdResult.openid;
                //}
                //string timeStamp = "";
                //string nonceStr = "";

                //Random MyRandom = new Random();
                //int RandomNum = MyRandom.Next(1001, 9999);
                //int RandomNum2 = MyRandom.Next(1001, 9999);
                //string sp_billno = DateTime.Now.ToString("HHssmmfff") + RandomNum.ToString() + RandomNum2.ToString();
                //ord.BusinessNo = sp_billno;
                //new PT_Order_HeaderB().ExsSql("UPDATE pt_order_header SET BusinessNo='" + sp_billno + "' WHERE ID='" + ord.ID + "'");

                //decimal payprice = 0.01M; // ord.SumPrice.Value;
                ////当前时间 yyyyMMdd
                //string date = DateTime.Now.ToString("yyyyMMdd");

                //timeStamp = TenPayV3Util.GetTimestamp();
                //nonceStr = TenPayV3Util.GetNoncestr();

                ////Tools.Common.WriteLog("微信订单参数", "", data);
                //if (TradeType == "JSAPI")
                //{
                //    TenPayV3UnifiedorderRequestData datainfo = new TenPayV3UnifiedorderRequestData(
                //    TenPayV3Info.AppId,
                //    TenPayV3Info.MchId,
                //    "社区好生活消费",
                //    sp_billno,
                //    (int)(payprice * 100),
                //    userip,
                //    TenPayV3Info.TenPayV3Notify,
                //    TenPayV3Type.JSAPI,
                //    openid,
                //    TenPayV3Info.Key,
                //    nonceStr);

                //    var res = TenPayV3.Unifiedorder(datainfo);
                //    string paySign = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, string.Format("prepay_id={0}", res.prepay_id), TenPayV3Info.Key);

                //    msg.result = new JObject(
                //            new JProperty("appId", TenPayV3Info.AppId),
                //            new JProperty("timeStamp", timeStamp),
                //            new JProperty("nonceStr", nonceStr),
                //            new JProperty("package", string.Format("prepay_id={0}", res.prepay_id)),
                //            new JProperty("signType", "MD5"),
                //            new JProperty("paySign", paySign)
                //        );
                //}
                //else if (TradeType == "MWEB")
                //{
                //    TenPayV3UnifiedorderRequestData dataInfo = new TenPayV3UnifiedorderRequestData(
                //    TenPayV3Info.AppId,
                //    TenPayV3Info.MchId,
                //    "社区好生活消费",
                //    sp_billno,
                //    (int)(payprice * 100),
                //    userip,
                //    TenPayV3Info.TenPayV3Notify,
                //    TenPayV3Type.MWEB,
                //    openid,
                //    TenPayV3Info.Key,
                //    nonceStr);

                //    var res = TenPayV3.Html5Order(dataInfo);

                //    msg.result = res.mweb_url;
                //}
                //Tools.Common.WriteLog("JSAPI参数" + JsonConvert.SerializeObject(msg));
            }
            catch (Exception ex)
            {
                string ss = ex.Message;

                Tools.Common.WriteLog("异常" + ss);
            }
        }
        #endregion

        #region 微信支付异步通知
        public void PayNotifyUrl(ref Msg_Result msg)
        {

            ResponseHandler resHandler = new ResponseHandler(null);

            string return_code = resHandler.GetParameter("return_code");
            string return_msg = resHandler.GetParameter("return_msg");

            string res = null;

            resHandler.SetKey(TenPayV3Info.Key);
            //验证请求是否从微信发过来（安全）
            if (resHandler.IsTenpaySign())
            {
                res = "success";

                //正确的订单处理
                string transaction_id = resHandler.GetParameter("transaction_id");
                string out_trade_no = resHandler.GetParameter("out_trade_no"); //订单号码
                string total_fee = resHandler.GetParameter("total_fee");  //订单金额

                Tools.Common.WriteLog("微信支付通知,微信支付订单号" + out_trade_no);

                //var db = new tongxiaoEntities();
                //var ord = db.pt_order_header.FirstOrDefault(p => p.BusinessNo == out_trade_no);
                //if (ord.Status == 0)
                //{
                //    ord.PayStatus = 1;
                //    ord.Status = 1;
                //    ord.PayType = "weixin";
                //    ord.PayTime = DateTime.Now;
                //    db.SaveChanges();

                //    if (ord.OrderType == "2") //购买万能券
                //    {
                //        var item = new PT_Order_ItemB().GetEntityFirst(p => p.OrderID == ord.ID);
                //        if (item != null)
                //        {
                //            new pt_user_couponb().Insert(new pt_user_coupon()
                //            {
                //                Type = "1",
                //                CID = item.ID,
                //                Title = item.Title,
                //                CValue = item.Point,
                //                Status = 1,
                //                CRUser = ord.CRUser,
                //                CRTime = DateTime.Now,
                //                Desp = "购买万能券"
                //            });

                //            //扣除存款
                //            new PT_User_AccountB().ChangeUserPoint("2", (int)ord.Price2, ord.CRUser.Value, "购买" + item.Title, "", ord.ID.ToString());

                //        }

                //    }


                //    #region 保存参数
                //    try
                //    {
                //        new PT_Order_PayInfoB().Insert(new pt_order_payinfo()
                //        {
                //            OrderID = ord.ID.ToString(),
                //            PayType = "weixin",
                //            appid = resHandler.GetParameter("appid"),
                //            mch_id = resHandler.GetParameter("mch_id"),
                //            device_info = resHandler.GetParameter("device_info"),
                //            nonce_str = resHandler.GetParameter("nonce_str"),
                //            sign = resHandler.GetParameter("sign"),
                //            result_code = resHandler.GetParameter("result_code"),
                //            err_code = resHandler.GetParameter("err_code"),
                //            err_code_des = resHandler.GetParameter("err_code_des"),
                //            openid = resHandler.GetParameter("openid"),
                //            is_subscribe = resHandler.GetParameter("is_subscribe"),
                //            trade_type = resHandler.GetParameter("trade_type"),
                //            bank_type = resHandler.GetParameter("bank_type"),
                //            total_fee = resHandler.GetParameter("total_fee"),
                //            settlement_total_fee = resHandler.GetParameter("settlement_total_fee"),
                //            fee_type = resHandler.GetParameter("fee_type"),
                //            cash_fee = resHandler.GetParameter("cash_fee"),
                //            cash_fee_type = resHandler.GetParameter("cash_fee_type"),
                //            coupon_fee = resHandler.GetParameter("coupon_fee"),
                //            coupon_count = resHandler.GetParameter("coupon_count"),
                //            coupon_type_n = resHandler.GetParameter("coupon_type_$n"),
                //            coupon_id_n = resHandler.GetParameter("coupon_id_$n"),
                //            coupon_fee_n = resHandler.GetParameter("coupon_fee_$n"),
                //            transaction_id = resHandler.GetParameter("transaction_id"),
                //            out_trade_no = resHandler.GetParameter("out_trade_no"),
                //            attach = resHandler.GetParameter("attach"),
                //            time_end = resHandler.GetParameter("time_end"),

                //        });
                //    }
                //    catch (Exception ex)
                //    {
                //        Tools.Common.WriteLog(ex.Message);
                //    }
                //    #endregion
                //}
                //else
                //{

                //}
            }
            else
            {
                res = "wrong";

                //错误的订单处理
            }

            string xml = string.Format(@"<xml><return_code><![CDATA[{0}]]></return_code><return_msg><![CDATA[{1}]]></return_msg></xml>", return_code, return_msg);

            msg.result = xml;
        }
        #endregion        

        #region 微信退款接口
        public void ReFund(ref Msg_Result msg, int orderid)
        {
            //var ord = new pt_order_headerb().GetEntity(p => p.ID == orderid);
            //if (ord == null)
            //{
            //    msg.error = "订单信息错误！";
            //    return;
            //}


            //string nonceStr = TenPayV3Util.GetNoncestr();
            //RequestHandler packageReqHandler = new RequestHandler(null);

            ////设置package订单参数
            //packageReqHandler.SetParameter("appid", TenPayV3Info.AppId);		  //公众账号ID
            //packageReqHandler.SetParameter("mch_id", TenPayV3Info.MchId);		  //商户号
            //packageReqHandler.SetParameter("out_trade_no", ord.BusinessNo);                 //填入商家订单号
            //packageReqHandler.SetParameter("out_refund_no", ord.BusinessNo + "1");                //填入退款订单号
            //packageReqHandler.SetParameter("total_fee", ((int)(ord.SumPrice * 100)).ToString());               //填入总金额
            //packageReqHandler.SetParameter("refund_fee", ((int)(ord.SumPrice * 100)).ToString());               //填入退款金额
            //packageReqHandler.SetParameter("op_user_id", TenPayV3Info.MchId);   //操作员Id，默认就是商户号
            //packageReqHandler.SetParameter("nonce_str", nonceStr);              //随机字符串
            //string sign = packageReqHandler.CreateMd5Sign("key", TenPayV3Info.Key);
            //packageReqHandler.SetParameter("sign", sign);	                    //签名
            ////退款需要post的数据
            //string data = packageReqHandler.ParseXML();

            ////退款接口地址
            //string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            ////本地或者服务器的证书位置（证书在微信支付申请成功发来的通知邮件中）
            //string cert = @"F:\apiclient_cert.p12";
            ////私钥（在安装证书时设置）
            //string password = "";
            //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            ////调用证书
            //X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);

            //#region 发起post请求
            //HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url);
            //webrequest.ClientCertificates.Add(cer);
            //webrequest.Method = "post";

            //byte[] postdatabyte = Encoding.UTF8.GetBytes(data);
            //webrequest.ContentLength = postdatabyte.Length;
            //Stream stream;
            //stream = webrequest.GetRequestStream();
            //stream.Write(postdatabyte, 0, postdatabyte.Length);
            //stream.Close();

            //HttpWebResponse httpWebResponse = (HttpWebResponse)webrequest.GetResponse();
            //StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            //string responseContent = streamReader.ReadToEnd();
            //#endregion

            //var res = XDocument.Parse(responseContent);

            //string result_code = res.Element("xml").Element("result_code").Value;
            //string out_refund_no = res.Element("xml").Element("out_refund_no").Value;
            //string refund_channel = res.Element("xml").Element("refund_channel").Value;//ORIGINAL—原路退款 BALANCE—退回到余额



        }
        #endregion

        #region 微信接入
        public bool Check(ref Msg_Result msg, string signature ,string timestamp,string nonce)
        {
            return WXHelp.checkSignature(signature, timestamp, nonce);
        }

        #endregion
    }
}
